package com.aizuda.service.handler;

import com.aizuda.service.anno.LongToStringIgnore;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;

import java.io.IOException;

/**
 * @author hjw
 * @description
 * @date 2025年06月26日 11:23
 */
public class ConditionalToStringSerializer extends JsonSerializer<Long> implements ContextualSerializer {
    private final boolean ignore;

    public ConditionalToStringSerializer() {
        this(false);
    }

    public ConditionalToStringSerializer(boolean ignore) {
        this.ignore = ignore;
    }

    @Override
    public void serialize(Long value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (ignore) {
            gen.writeNumber(value);
        } else {
            gen.writeString(value == null ? null : value.toString());
        }
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) {
        if (property != null && property.getAnnotation(LongToStringIgnore.class) != null) {
            return new ConditionalToStringSerializer(true);
        }
        return new ConditionalToStringSerializer(false);
    }
}
